package com.ruoyi.door.service;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSONObject;
import com.easy.query.api.proxy.client.EasyEntityQuery;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.order.OrderNoGenerator;
import com.ruoyi.door.controller.app.orderinfo.vo.AppOrderRefundReqVO;
import com.ruoyi.door.domain.DoorOrder;
import com.ruoyi.door.utils.baofu.BaoFuJuHeService;
import com.ruoyi.door.utils.baofu.BaoFuXieYiService;
import com.ruoyi.door.utils.baofu.entity.ResultMasterEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class DoorOrderRefundService {
    @Autowired
    private EasyEntityQuery easyEntityQuery;
    @Autowired
    private BaoFuXieYiService baoFuXieYiService;
    @Autowired
    private BaoFuJuHeService baoFuJuHeService;

    public void submit(AppOrderRefundReqVO reqVO) {
        DoorOrder orderInfo = easyEntityQuery.queryable(DoorOrder.class).where(d -> {
            d.orderNo().eq(reqVO.getOrderNo());
        }).firstOrNull();
        if (ObjectUtil.isNull(orderInfo)) {
            throw new ServiceException("订单不存在");
        }
        if (orderInfo.getOrderStatus() == 0L) {
            throw new ServiceException("未支付订单无法退款");
        }
        if (orderInfo.getOrderStatus() == 3L) {
            throw new ServiceException("已退款订单无法退款");
        }
        orderInfo.setRefundNo(OrderNoGenerator.generateOrderNo1());
        //微信
        if (orderInfo.getPayChannel().equals("1")) {

            ResultMasterEntity refund = baoFuJuHeService.refund(orderInfo);
            if (refund.getReturnCode().equals("SUCCESS")){
                orderInfo.setOrderStatus(2L);
                orderInfo.setRefundCreateTime(DateUtils.getNowDate());
                easyEntityQuery.updatable(orderInfo).executeRows();
            }
        }
        //银行卡
        if (orderInfo.getPayChannel().equals("2")) {
            JSONObject refund = baoFuXieYiService.refund(orderInfo);
            if (refund.getString("resp_code").equals("0000")){
                orderInfo.setOrderStatus(2L);
                orderInfo.setRefundCreateTime(DateUtils.getNowDate());
                easyEntityQuery.updatable(orderInfo).executeRows();
            }
        }
    }
}
